<template>
  <div class="page-container">
    <div class="toolbar">
      <el-row>
        <el-tabs type="border-card">
          <el-tab-pane label="基本信息">
            <el-form
              :inline="true"
              :model="dataForm"
              label-width="140px"
              style="text-align:left;"
              ref="dataForm"
              :rules="dataFormRules"
              class="form"
            >
              <el-row style="margin-top: -20px;" class="searchDialog-input">
                <el-divider content-position="center">
                  <span style="font-size:16px;font-weight:800">基本信息</span>
                </el-divider>
                <el-form-item label="供应商范围编码：" prop="rangeCode">
                  <el-input v-model="dataForm.rangeCode" placeholder="请输入" :disabled="isView ==1"></el-input>
                </el-form-item>
                <el-form-item label="供应范围名称：" prop="rangeName">
                  <el-input v-model="dataForm.rangeName" placeholder="请输入" :disabled="isView ==1"></el-input>
                </el-form-item>
                <!-- TODO 非供应商平台展示,临时处理 -->
                <el-form-item label="选择供应商：" prop="supplierId" v-if="deptType != 1" required>
                  <el-select v-model="dataForm.supplierId" :disabled="rangeId != null">
                    <el-option
                      v-for="item in supplierList"
                      :key="item.id"
                      :label="item.supplierName"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-row>
            </el-form>
            <div class="tool-wrap" v-if="isView !=1">
              <div class="left-area">
                <el-button-group>
                  <el-button type="primary" size="small" @click="submitForm()">保存</el-button>
                  <el-button type="primary" size="small" @click="$router.go(-1)">取消</el-button>
                </el-button-group>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-row>
    </div>

    <div class="toolbar" v-if="rangeId != null ">
      <el-tabs type="border-card">
        <el-tab-pane label="选择商品" v-if="isView !=1">
          <el-container>
            <el-container>
              <el-aside width="320px">
                <el-card class="box-card">
                  <div style="height:550px;overflow-y:auto;">
                    <el-tree
                      :data="categoryData"
                      :filter-node-method="filterNode"
                      :highlight-current="true"
                      :props="defaultProps"
                      @node-click="thisTreeClick"
                      ref="tree"
                    ></el-tree>
                  </div>
                </el-card>
              </el-aside>
              <el-main>
                <el-dialog
                  title="商品列表"
                  width="60%"
                  :visible.sync="categoryTreeNodeProductDialogVisible"
                  :close-on-click-modal="false"
                >
                  <el-form :inline="true" :model="productFilters" ref="productFilters" size="small">
                    <el-form-item prop="chineseName" label="商品名称:">
                      <el-input v-model="productFilters.chineseName" placeholder="商品名称" />
                    </el-form-item>
                    <el-form-item prop="code" label="商品编码:">
                      <el-input v-model="productFilters.code" placeholder="商品编码" />
                    </el-form-item>
                    <el-form-item label="商品品牌:" prop="brandId">
                      <el-select
                        v-model="productFilters.brandId"
                        style="width: 200px"
                        placeholder="商品品牌"
                      >
                        <el-option
                          v-for="item in brandList"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item>
                      <kt-button
                        icon="fa fa-search"
                        :label="$t('action.search')"
                        type="primary"
                        @click="findProductPage"
                      />
                    </el-form-item>
                    <el-form-item>
                      <kt-button
                        icon="fa fa-refresh"
                        :label="$t('action.reset')"
                        type="primary"
                        @click="resetProductFiltersForm('productFilters')"
                      />
                    </el-form-item>
                  </el-form>
                  <el-table
                    :data="productList"
                    v-loading="productListLoading"
                    size="small"
                    align="align"
                    style="width: 100%"
                    :max-height="450"
                    :stripe="true"
                    @selection-change="selectionProductChange"
                    :header-cell-style="{ 'color': '#FFF','background-color': '#2F4554'}"
                  >
                    <el-table-column type="selection" align="center" width="55"></el-table-column>
                    <el-table-column prop="storeName" label="所属店铺"></el-table-column>
                    <el-table-column prop="chineseName" label="商品名称"></el-table-column>
                    <el-table-column prop="fullNamePath" label="商品类目"></el-table-column>
                    <el-table-column prop="brandName" label="商品品牌"></el-table-column>
                    <el-table-column prop="code" label="商品编码"></el-table-column>
                  </el-table>

                  <!--分页栏-->
                  <div class="toolbar" style="padding:10px;">
                    <el-pagination
                      layout="total, prev, pager, next, jumper,sizes"
                      @current-change="refreshPageRequest"
                      @size-change="handleSizeChange"
                      :current-page="productFilters.start"
                      :page-size="productFilters.limit"
                      :total="productTotal"
                      style="float:right;"
                      :page-sizes="[10, 20, 30, 40]"
                    ></el-pagination>
                  </div>
                  <div slot="footer" class="dialog-footer" style="text-align:center;">
                    <el-button
                      size="small"
                      @click.native="categoryTreeNodeProductDialogVisible = false"
                    >{{ $t("action.cancel") }}</el-button>
                    <el-button
                      size="small"
                      type="primary"
                      @click="saveSupplierProduct"
                      :loading="submitLoading"
                    >
                      {{
                      $t("action.submit") }}
                    </el-button>
                  </div>
                </el-dialog>
                <div v-if="refreshRangeProductDialogVisible">
                  <el-form>
                    <div class="tool-wrap">
                      <el-row class="search-button">
                        <el-form-item>
                          <el-button
                            type="primary"
                            size="small"
                            @click="addForm()"
                            icon="el-icon-plus"
                          >新增</el-button>
                        </el-form-item>
                      </el-row>
                    </div>
                  </el-form>
                  <div class="table-wrap">
                    <el-table
                      :data="rangProductList"
                      v-loading="rangProductListLoading"
                      style="width:100%;"
                      :header-cell-style="{ 'color': '#FFF','background-color': '#2F4554'}"
                    >
                      <el-table-column prop="productCode" label="商品编码"></el-table-column>
                      <el-table-column prop="productName" label="商品名称"></el-table-column>
                      <el-table-column prop="categoryCode" label="所属类目编码"></el-table-column>
                      <el-table-column label="创建日期" prop="createTime" align="center"></el-table-column>
                      <el-table-column label="操作" align="center">
                        <template slot-scope="scope">
                          <!-- <el-button size="mini" type="primary" v-if="scope.row.status != 1 && deptType == 1" @click="handleEdit(scope)">编辑</el-button> -->
                          <el-button size="mini" type="primary" @click="handleDelete(scope.row)">删除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <!--分页栏-->
                    <div class="toolbar" style="padding:10px;">
                      <el-pagination
                        layout="total, prev, pager, next, jumper,sizes"
                        @current-change="refreshRangeProductPage"
                        :current-page="searchFilters.pageNum"
                        :page-size="searchFilters.pageSize"
                        :total="rangProductTotal"
                        style="float:right;"
                        :page-sizes="[10, 20, 30, 40]"
                        @size-change="handleRangeProductSizeChange"
                      ></el-pagination>
                    </div>
                  </div>
                </div>
              </el-main>
            </el-container>
          </el-container>
        </el-tab-pane>
        <el-tab-pane label="已选择商品" v-if="isView ==1">
          <div class="table-wrap">
            <el-table
              :data="rangProductList"
              v-loading="rangProductListLoading"
              style="width:100%;"
              :header-cell-style="{ 'color': '#FFF','background-color': '#2F4554'}"
            >
              <el-table-column prop="productCode" label="商品编码"></el-table-column>
              <el-table-column prop="productName" label="商品名称"></el-table-column>
              <el-table-column prop="categoryCode" label="所属类目编码"></el-table-column>
              <el-table-column label="创建日期" prop="createTime" align="center"></el-table-column>
              <el-table-column label="操作" align="center" v-if="isView != 1">
                <template slot-scope="scope">
                  <!-- <el-button size="mini" type="primary" v-if="scope.row.status != 1 && deptType == 1" @click="handleEdit(scope)">编辑</el-button> -->
                  <el-button size="mini" type="primary" @click="handleDelete(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!--分页栏-->
            <div class="toolbar" style="padding:10px;">
              <el-pagination
                layout="total, prev, pager, next, jumper,sizes"
                @current-change="refreshRangeProductPage"
                :current-page="searchFilters.pageNum"
                :page-size="searchFilters.pageSize"
                :total="rangProductTotal"
                style="float:right;"
                :page-sizes="[10, 20, 30, 40]"
                @size-change="handleRangeProductSizeChange"
              ></el-pagination>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>
<script>
import ThemePicker from "@/components/ThemePicker";
import LangSelector from "@/components/LangSelector";
import VDistpicker from "v-distpicker";
import elTree from "@/views/tree/src/tree.vue";
import KtButton from "@/views/Core/KtButton";

export default {
  components: {
    ThemePicker,
    LangSelector,
    VDistpicker,
    elTree,
    KtButton,
  },

  //2.2 数据初始化区
  data() {
    return {
      dataForm: {
        id: null,
        rangeCode: null,
        rangeName: null,
      },
      //trigger 为blur 表示丢失焦点;为change 表示值发生变化;
      dataFormRules: {
        rangeCode: [
          { required: true, message: "请输入供应商范围编码", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur",
          },
          {
            required: true,
            message: "请输入供应商范围编码",
            trigger: "change",
          },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "change",
          },
        ],
        rangeName: [
          { required: true, message: "请输入供应范围名称", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur",
          },
          { required: true, message: "请输入供应范围名称", trigger: "change" },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "change",
          },
        ],
        supplierId:[
          { required: true, message: "请选择供应商", trigger: "change" },
        ]
      },
      rangeId: this.$route.query.id,
      isView: this.$route.query.isView || 2,
      categoryData: [],
      categoryId: 1,
      defaultProps: {
        children: "categoryList",
        label: "name",
      },
      brandList: [],
      //商品列表条件查询
      productFilters: {
        start: 1,
        limit: 10,
        chineseName: null,
        brandId: null,
        code: null,
        flag: 1,
      },
      currentCategoryId: null,
      currentCategoryCode: null,
      productList: [],
      productListLoading: false,
      productTotal: 0,
      selectionProduct: [],
      submitLoading: false, //保存商品loading
      categoryTreeNodeProductDialogVisible: false,
      rangProductList: [], //供应商范围商品
      rangProductListLoading: false,
      rangProductTotal: 0,
      searchFilters: {
        pageNum: 1,
        pageSize: 10,
      },
      refreshRangeProductDialogVisible: false,
      deptType: localStorage.getItem("deptType"),
      supplierList:[],
    };
  },
  methods: {
    //查询供应商列表
    querySupplierList(){
      let param = {
        pageNum: 1,
        pageSize: 1000,
        status:1
      };
      this.utils.request.supplierInformationListPage(param,res =>{
        if(res.code == '0000' && res.data.rows && res.data.rows.length > 0){
          this.supplierList = res.data.rows;
        }else{
          this.supplierList = [];
        }
      });
    },
    //获取范围详情
    getDetail() {
      let this_ = this;
      this_.refreshRangeProductDialogVisible = false;
      let params = {};
      params.id = this.rangeId;
      this.utils.request.SupplierRangeManageDetail(params, function (res) {
        if (res.code === "0000") {
          this_.dataForm = res.data;
          this_.queryCategory();
        } else {
          this_.$message({ message: "操作失败, " + data.msg, type: "error" });
        }
      });
    },
    //保存基本信息
    submitForm: function () {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          if (this.rangeId) {
            this.dataForm.id = this.rangeId;
          }
          this.utils.request.saveSupplierRangeManage(this.dataForm, (res) => {
            if (res.code == "0000" && res.data) {
              if (!this.rangeId || this.rangeId == null) {
                this.rangeId = res.data;
                this.$router.push({ query: { id: res.data } });
              }
              this.getDetail();
            }
          });
        }
      });
    },
    //主界面查询所有商品类目
    queryCategory: function () {
      let this_ = this;
      this.categoryData = [];
      let params = {};
      params.id = this_.categoryId;
      this.utils.request.queryBehindCategory(params, function (data) {
        if (data.data != null) {
          this_.categoryData = data.data;
        }
      });
    },
    //类目节点过滤
    filterNode: function (value, data, node) {
      if (!value) {
        return true;
      }
      let level = node.level;
      let _array = []; //这里使用数组存储 只是为了存储值。
      if (data.name.indexOf(value) !== -1) {
        node.isCurrent = true;
      } else {
        node.isCurrent = false;
      }
      this.getReturnNode(node, _array, value);
      let result = false;
      _array.forEach((item) => {
        result = result || item;
      });
      return result;
    },
    getReturnNode(node, _array, value) {
      let isPass =
        node.data && node.data.name && node.data.name.indexOf(value) !== -1;
      isPass ? _array.push(isPass) : "";
      if (!isPass && node.level != 1 && node.parent) {
        this.getReturnNode(node.parent, _array, value);
      }
    },
    thisTreeClick(data) {
      if (!data.categoryList || data.categoryList.length <= 0) {
        this.currentCategoryId = data.id;
        this.currentCategoryCode = data.categoryCode;
        this.refreshRangeProductDialogVisible = true;
        this.queryRangeProduct();
      } else {
        this.currentCategoryId = null;
        this.currentCategoryCode = null;
        this.refreshRangeProductDialogVisible = false;
      }
    },
    // ---------范围商品 start --------
    //删除范围商品
    handleDelete(row) {
      this.$confirm("确认删除该商品吗？", "提示", { type: "info" }).then(() => {
        this.utils.request.updateSupplierRangeProduct(
          { id: row.id, deleteFlag: 1 },
          (res) => {
            if (res.code == "0000") {
              this.queryRangeProduct();
              this.$message({ message: "操作成功！", type: "success" });
            }
          }
        );
      });
    },
    // 每页数据刷新
    refreshRangeProductPage: function (pageNum) {
      this.searchFilters.pageNum = pageNum;
      this.queryRangeProduct();
    },
    // 每页条数刷新
    handleRangeProductSizeChange: function (pageSize) {
      this.searchFilters.pageSize = pageSize;
      this.queryRangeProduct();
    },
    // ---------弹框选择商品 start-----------
    addForm() {
      this.categoryTreeNodeProductDialogVisible = true;
      this.selectionProduct = []; //清空已选中的
      this.queryProductBrand();
      this.findProductPage();
    },
    queryRangeProduct() {
      this.rangProductListLoading = true;
      this.searchFilters.rangeId = this.rangeId;
      this.searchFilters.categoryId = this.currentCategoryId;
      this.utils.request.querySupplierRangeProductList(
        this.searchFilters,
        (res) => {
          if (res.code == "0000" && res.data && res.data.rows) {
            this.rangProductList = res.data.rows;
            this.rangProductTotal = res.data.total;
          } else {
            this.rangProductList = [];
            this.rangProductTotal = 0;
          }
          this.rangProductListLoading = false;
        }
      );
    },
    // 获取分页数据
    findProductPage: function (params) {
      let this_ = this;
      this_.productFilters.productCategoryId = this_.currentCategoryId;
      this_.productListLoading = true;
      this.utils.request.queryShopProductPage(this_.productFilters, (res) => {
        if (res.code == "0000" && res.data && res.data.rows) {
          this_.productList = res.data.rows;
          this_.productTotal = Number(res.data.total);
        }
        this_.productListLoading = false;
      });
    },
    //查询所有品牌
    queryProductBrand() {
      let _this = this;
      this.utils.request.queryProductBrand({}, function (data) {
        if (data.data != null) {
          _this.brandList = data.data;
        }
      });
    },
    //商品列表条件 重置
    resetProductFiltersForm(formName) {
      this.$refs[formName].resetFields();
      this.findProductPage();
    },
    // 每页数据刷新
    refreshPageRequest: function (pageNum) {
      this.productFilters.start = pageNum;
      this.findProductPage();
    },
    // 每页条数刷新
    handleSizeChange: function (pageSize) {
      this.productFilters.limit = pageSize;
      this.findProductPage();
    },
    //商品列表勾选数据
    selectionProductChange: function (params) {
      this.selectionProduct = params;
    },
    //保存供应商商品
    saveSupplierProduct() {
      if (!this.selectionProduct || this.selectionProduct.length <= 0) {
        this.$message({ message: "请选择商品!", type: "error" });
        return;
      }
      this.submitLoading = true;
      let rangeProductList = [];
      this.selectionProduct.forEach((item) => {
        let rangeProduct = {
          rangeId: this.rangeId,
          productId: item.id,
          productCode: item.code,
          productName: item.chineseName,
          categoryId: this.currentCategoryId,
          categoryCode: this.currentCategoryCode,
          supplierId:this.dataForm.supplierId || null
        };
        rangeProductList.push(rangeProduct);
      });
      let param = {
        requests: rangeProductList,
      };
      this.utils.request.bacthSupplierRangeProduct(param, (res) => {
        if (res.code == "0000") {
          this.categoryTreeNodeProductDialogVisible = false;
          this.queryRangeProduct();
          this.$message({ message: "操作成功！", type: "success" });
        }
        this.submitLoading = false;
      });
    },
    // ---------弹框选择商品 end-----------
  },
  //1.初始化页面调用方法(dom元素绑定后再执行初始化数据操作)
  mounted() {
    if (this.rangeId) {
      this.getDetail();
    }
    if(this.deptType != 1){
      this.querySupplierList();
    }
    if (this.isView == 1) {
      this.queryRangeProduct();
    }
  },
};
</script>
<style lang="scss" scoped>
/* ele组件样式重置 */
.common-content {
  padding: 10px;
  box-sizing: border-box;

  .search-wrap /deep/ {
    .el-form-item__label {
      height: 32px;
      line-height: 32px;
    }

    .el-form-item__content {
      height: 32px;
      line-height: 32px;
      width: 150px;
    }

    .el-input--mini .el-input__inner {
      height: 32px;
      line-height: 32px;
    }

    .el-date-editor.el-input,
    .el-date-editor.el-input__inner {
      width: 150px;
    }
  }

  /* 多日期样式重置 */
  .el-dater /deep/ .el-form-item__content {
    width: 330px;
  }

  /* 通用工具部分样式 */
  .tool-wrap {
    width: 100%;
    height: auto;
    position: relative;
    overflow: hidden;

    .left-area {
      float: left;
      width: 50%;
      text-align: left;

      button {
        margin-right: 15px;
        border-radius: 5px;
      }
    }

    .right-area {
      float: right;
      width: 50%;
      text-align: right;
    }
  }

  /* 表格部分样式 */
  .table-wrap {
    width: 100%;
    max-height: 600px;
    margin-top: 20px;
  }

  /* 弹窗样式 */
  .dialog-wrap /deep/ .el-dialog__footer {
    text-align: center !important;
  }
}
</style>
